package me.wangqu.weiyouqu.web.rest;

import com.codahale.metrics.annotation.Timed;
import me.wangqu.weiyouqu.domain.Dict;
import me.wangqu.weiyouqu.repository.DictRepository;
import me.wangqu.weiyouqu.security.AuthoritiesConstants;
import me.wangqu.weiyouqu.web.rest.util.HeaderUtil;
import me.wangqu.weiyouqu.web.rest.util.PaginationUtil;
import me.wangqu.weiyouqu.web.rest.dto.DictDTO;
import me.wangqu.weiyouqu.web.rest.mapper.DictMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing Dict.
 */
@RestController
@RequestMapping("/api")
public class DictResource {

    private final Logger log = LoggerFactory.getLogger(DictResource.class);

    @Inject
    private DictRepository dictRepository;

    @Inject
    private DictMapper dictMapper;

    /**
     * 查询字典对应类型信息
     * @param type
     * @param pageable
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping(value = "/dicts/type/{type}",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Transactional(readOnly = true)
    public ResponseEntity<List<DictDTO>> getDictsByType(@PathVariable Integer type, Pageable pageable)
            throws URISyntaxException {
        log.debug("REST request to get a page of Dicts by type");
        Page<Dict> page = dictRepository.findByType(type, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/dicts");
        return new ResponseEntity<>(dictMapper.dictsToDictDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * POST  /dicts : Create a new dict.
     *
     * @param dictDTO the dictDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new dictDTO, or with status 400 (Bad Request) if the dict has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/dicts",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<DictDTO> createDict(@Valid @RequestBody DictDTO dictDTO) throws URISyntaxException {
        log.debug("REST request to save Dict : {}", dictDTO);
        if (dictDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("dict", "idexists", "A new dict cannot already have an ID")).body(null);
        }
        Dict dict = dictMapper.dictDTOToDict(dictDTO);
        dict = dictRepository.save(dict);
        DictDTO result = dictMapper.dictToDictDTO(dict);
        return ResponseEntity.created(new URI("/api/dicts/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("dict", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /dicts : Updates an existing dict.
     *
     * @param dictDTO the dictDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated dictDTO,
     * or with status 400 (Bad Request) if the dictDTO is not valid,
     * or with status 500 (Internal Server Error) if the dictDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/dicts",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<DictDTO> updateDict(@Valid @RequestBody DictDTO dictDTO) throws URISyntaxException {
        log.debug("REST request to update Dict : {}", dictDTO);
        if (dictDTO.getId() == null) {
            return createDict(dictDTO);
        }
        Dict dict = dictMapper.dictDTOToDict(dictDTO);
        dict = dictRepository.save(dict);
        DictDTO result = dictMapper.dictToDictDTO(dict);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("dict", dictDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /dicts : get all the dicts.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of dicts in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value = "/dicts",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<DictDTO>> getAllDicts(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Dicts");
        Page<Dict> page = dictRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/dicts");
        return new ResponseEntity<>(dictMapper.dictsToDictDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * GET  /dicts/:id : get the "id" dict.
     *
     * @param id the id of the dictDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the dictDTO, or with status 404 (Not Found)
     */
    @RequestMapping(value = "/dicts/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<DictDTO> getDict(@PathVariable Long id) {
        log.debug("REST request to get Dict : {}", id);
        Dict dict = dictRepository.findOne(id);
        DictDTO dictDTO = dictMapper.dictToDictDTO(dict);
        return Optional.ofNullable(dictDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /dicts/:id : delete the "id" dict.
     *
     * @param id the id of the dictDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @RequestMapping(value = "/dicts/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteDict(@PathVariable Long id) {
        log.debug("REST request to delete Dict : {}", id);
        dictRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("dict", id.toString())).build();
    }

}
